package pl.edu.agh.mguesser.ui;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import pl.edu.agh.mguesser.exception.MusicGuesserRuntimeException;
import pl.edu.agh.mguesser.player.Player;
import pl.edu.agh.mguesser.playlist.parser.M3UPlaylistParser;
import pl.edu.agh.mguesser.playlist.parser.PlaylistParserException;

/**
 * @author keiran
 */
@Controller
public class UIBootstrapper {

    @Autowired
    private ClassPathXmlApplicationContext applicationContext;
    @Autowired
    private Player player;
    @Autowired
    private Window window;

    @PostConstruct
    public void postConstruct() {
        try {
            Path path = Paths.get(getClass().getClassLoader().getResource("songs/playlist.m3u").toURI());
            player.setPlaylist(new M3UPlaylistParser().parse(path));

            javax.swing.SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    createAndShowGUI();
                }
            });

        } catch (URISyntaxException | PlaylistParserException ex) {
            throw new MusicGuesserRuntimeException(ex);

        }
    }

    private void createAndShowGUI() {
        window.addWindowListener(new CustomWindowListener());

        window.setSize(SizeConstants.WINDOW_WIDTH, SizeConstants.WINDOW_HEIGHT);
        window.setVisible(true);
    }

    private class CustomWindowListener implements WindowListener {

        @Override
        public void windowOpened(WindowEvent event) {
        }

        @Override
        public void windowClosing(WindowEvent event) {
        }

        @Override
        public void windowClosed(WindowEvent event) {
            applicationContext.destroy();
        }

        @Override
        public void windowIconified(WindowEvent event) {
        }

        @Override
        public void windowDeiconified(WindowEvent event) {
        }

        @Override
        public void windowActivated(WindowEvent event) {
        }

        @Override
        public void windowDeactivated(WindowEvent event) {
        }
        
    }
    
}
